#include <stdint.h>
#include <math.h>

#include "include/combat.h"
#include "include/pointers.h"
#include "include/thiscall.h"
#include "include/log.h"

/* This code crashes the game client fairly often (as is expected)
 * I'm currently working on finding the mutex (if any is available)
 * if I cannot find one I have to patch the game code to use a mutex of my own.
 */

uint32_t
TargetObject(struct RomObject *target)
{
    uint32_t argList[] = {(uint32_t)target};
    return ThisCall(ROMOBJECT_SETTARGET, (*BASE_PTR)->player, 1, argList);
}


/* Monster is not actually getting selected, remoted due to crash */
int
SelectNearestMonster(struct BotData *botData)
{

    /* Wait for our mutex */
    if(WaitForSingleObject(botData->environment.mutex, INFINITE) != WAIT_OBJECT_0)
    {
        LogWrite(botData, "Error: WaitForSingleObject failed with 0x%lX", GetLastError());
        return 0;
    }
    
    for(unsigned int i = 0; i < botData->environment.size; i++)
    {
        register struct RomObject *object = botData->environment.object[i];
        if( object->objectType == TYPE_MONSTER &&
            fabs((*BASE_PTR)->player->coordX - object->coordX) < 150.0 &&
            fabs((*BASE_PTR)->player->coordZ - object->coordZ) < 150.0 &&
            fabs((*BASE_PTR)->player->coordY - object->coordY) < 150.0)
        {
            LogWrite(botData, "Selecting: '%s' %u", object->name == NULL ? "no name" : object->name, object->objectId);
            TargetObject(object);
            LogWrite(botData, "Done.");
            if(ReleaseMutex(botData->environment.mutex) == 0)
                LogWrite(botData, "Error: ReleaseMutex failed with %lX (You're fucked)", GetLastError());
            return 1;
        }
    }

    if(ReleaseMutex(botData->environment.mutex) == 0)
        LogWrite(botData, "Error: ReleaseMutex failed with 0x%lX (You're fucked)", GetLastError());

    LogWrite(botData, "Could not select a monster (no monster suitable out of %u nearby objects)", botData->environment.size);
    return 0;
}
